package Classic150;

import java.util.ArrayList;
import java.util.List;

public class 全排列 {

    int len;
    int[] nums;
    boolean[] selected;
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();

    /*
        使用selected布尔数组替代set进行剪枝
     */
    public List<List<Integer>> permute(int[] nums) {
        this.nums = nums;
        len = nums.length;
        selected = new boolean[len];
        backTracking();
        return res;
    }

    private void backTracking() {
        if (path.size() == len) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < len; i++) {
            if (!selected[i]) {
                path.add(nums[i]);
                selected[i] = true;
                backTracking();
                path.removeLast();
                selected[i] = false;
            }
        }
    }
}
